package net.galluzzo.wave.orthopermubot.textviewproc;

import net.galluzzo.wave.orthopermubot.permutation.Permutation;

import com.google.wave.api.Range;
import com.google.wave.api.TextView;

/**
 * A text view processor that alters the given text view by replacing each word
 * in turn with a permutation of that word, as determined by
 * {@link #getWordPermutation()}.
 * 
 * @param textView  The text view to alter
 */
public class WordBasedTextViewProcessor implements TextViewProcessor {
	protected Permutation wordPermutation;
	
	/**
	 * Creates a new word-based text view processor that applies the given
	 * permutation to each word in the text views it processes.
	 * 
	 * @param wordPermutation  The word permutation to apply
	 */
	public WordBasedTextViewProcessor( Permutation wordPermutation ) {
		this.wordPermutation = wordPermutation;
	}
	
	public void processTextView( TextView textView ) {
		String text = textView.getText();
		boolean lastCharWasWord = false;
		int wordStart = 0;
		int newWordStart = 0;
		
		// Split the text view into words and replace each word.
		for ( int i = 0; i < text.length(); i++ ) {
			char c = text.charAt( i );
			if ( Character.isLetterOrDigit( c ) ) {
				lastCharWasWord = true;
			} else {
				if ( lastCharWasWord ) {
					String lastWord = text.substring( wordStart, i );
					String newWord = wordPermutation.permute( lastWord );
					if ( !lastWord.equals( newWord ) ) {
						textView.replace( new Range( newWordStart,
								newWordStart + lastWord.length() ), newWord );
					}
					wordStart = i;
					newWordStart += newWord.length();
				}
				wordStart++;
				newWordStart++;
				lastCharWasWord = false;
			}
		}
		
		if ( lastCharWasWord ) {
			String lastWord = text.substring( wordStart, text.length() );
			String newWord = wordPermutation.permute( lastWord );
			textView.replace( new Range( newWordStart,
					newWordStart + lastWord.length() ), newWord );
		}
	}
}
